<template>
    <el-space class="fill-width attachMore-button" wrap>
        <el-text tag="b">字典类型：</el-text>
        <slot name="prepend"/>
        <template v-for="{value,label} in state.list" :key="value">
            <div @click="onSelect(value)">
                <slot :active="state.active===value" :record="{value,label}" name="button"/>
                <el-button
                        v-if="!slots.button"
                        :type="state.active===value?'primary':<any>''"
                        :value="value"
                        class="mr-2"
                        plain
                >
                    {{ label }}
                </el-button>
            </div>
        </template>
        <slot name="append"/>
    </el-space>
</template>

<script lang="ts" setup>

import {onMounted, reactive, useSlots} from "vue";
import {CommonApi} from "@/api/system/common.api";
import {AttachMore} from "@/api/types";

interface Props {
    params: AttachMore;
    active?: string;
    autoSelect?: boolean;
}

const {params, autoSelect} = withDefaults(defineProps<Props>(), {
    autoSelect: false,
});

const slots = useSlots();
const emits = defineEmits(["update:active"]);
const commonApi = new CommonApi();
const state = reactive<{
    list: any[],
    active: string,
}>({
    list: [],
    active: "",
});

function init() {
    commonApi.attachMore([params]).then(res => {
        if (res.ok) {
            //@ts-ignore
            state.list = res.data[`${params.target}Options`];
            if (autoSelect) {
                onSelect((state.list[0] as any).value);
            }
        }
    });
}

function onSelect(value: string) {
    state.active = value;
    emits("update:active", value);
}


onMounted(() => {
    init();
});

</script>

<style lang="scss" scoped>
.attachMore-button {
  .active {

  }
}
</style>
